/**
 * Copyright (C) <2023> <Boundivore> <boundivore@foxmail.com>
 * <p>
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Apache License, Version 2.0
 * as published by the Apache Software Foundation.
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License, Version 2.0 for more details.
 * <p>
 * You should have received a copy of the Apache License, Version 2.0
 * along with this program; if not, you can obtain a copy at
 * http://www.apache.org/licenses/LICENSE-2.0.
 */
import { useCallback, useState } from 'react';
import { Card, Space, Tooltip, Button } from 'antd';
import { PlusCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { t } from 'i18next';
import { useGroupManager } from '../hooks/useGroupManager';
import { useConfigState } from '../hooks/useConfigState';
import { ConfigGroupVo } from '@/api/interface';
import NodeListModal from './nodeListModal';

export const GroupManager: React.FC = () => {
	const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
	const { handleClick } = useGroupManager();
	const { configGroupInfo, currentGroupIndex, setCurrentGroupIndex } = useConfigState();

	const handleModalOk = useCallback(
		(targetGroupIndex: number, data: ConfigGroupVo[]) => {
			// 新建分组，添加到其他分组
			setIsModalOpen(false);
			if (targetGroupIndex >= data.length) {
				setCurrentGroupIndex(data.length - 1);
			} else {
				setCurrentGroupIndex(targetGroupIndex);
			}
		},
		[setCurrentGroupIndex]
	);

	const handleModalCancel = useCallback(() => {
		setIsModalOpen(false);
	}, []);

	return (
		<>
			<Card
				title={
					<Space>
						{t('setGroup')}
						<Tooltip title={t('groupPrompt')}>
							<QuestionCircleOutlined />
						</Tooltip>
					</Space>
				}
				bordered={true}
				className="h-[100%] overflow-y-auto max-h-[690px] min-w-[130px]"
			>
				<Space direction="vertical">
					{configGroupInfo.map((_group, index) => {
						return (
							<Space key={index}>
								<Button
									key={index}
									size="middle"
									type={index === currentGroupIndex ? 'primary' : 'default'}
									onClick={() => {
										handleClick(index);
									}}
								>
									{t('group', { name: index + 1 })}
								</Button>
								<PlusCircleOutlined
									style={{ fontSize: '16px' }}
									onClick={() => {
										handleClick(index);
										setIsModalOpen(true);
									}}
								/>
							</Space>
						);
					})}
				</Space>
			</Card>
			{isModalOpen ? (
				<NodeListModal
					isModalOpen={isModalOpen}
					groupIndex={currentGroupIndex}
					handleOk={handleModalOk}
					handleCancel={handleModalCancel}
				/>
			) : null}
		</>
	);
};
